using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;
using hao_Common.Dapper.Db;
using hao_Common.Dapper.Repository;
using hao_Model;

namespace hao_Reppsitory.Product
{
    /// <summary>
    /// 商品留言仓储实现
    /// </summary>
    public class ProductCommentRepository : DapperGenericRepository<ProductComment>, IProductCommentRepository
    {
        public ProductCommentRepository(IDbConnectionFactory connectionFactory) : base(connectionFactory) { }

        /// <summary>
        /// 根据商品ID获取留言列表（分页）
        /// </summary>
        public async Task<(List<ProductComment> comments, int total)> GetCommentsByProductIdAsync(Guid productId, int page, int pageSize)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var offset = (page - 1) * pageSize;
            
            // 获取顶级留言（ParentId为null）
            var sql = @"
                SELECT * FROM ProductComment 
                WHERE ProductId = @ProductId AND ParentId IS NULL AND IsDeleted = 0
                ORDER BY CreatedAt DESC
                LIMIT @PageSize OFFSET @Offset";
            
            var countSql = @"
                SELECT COUNT(1) FROM ProductComment 
                WHERE ProductId = @ProductId AND ParentId IS NULL AND IsDeleted = 0";
            
            var comments = await connection.QueryAsync<ProductComment>(sql, new 
            { 
                ProductId = productId, 
                Offset = offset, 
                PageSize = pageSize 
            });
            
            var total = await connection.QuerySingleAsync<int>(countSql, new { ProductId = productId });
            
            return (comments.ToList(), total);
        }

        /// <summary>
        /// 根据父留言ID获取回复列表
        /// </summary>
        public async Task<List<ProductComment>> GetRepliesByParentIdAsync(Guid parentId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                SELECT * FROM ProductComment 
                WHERE ParentId = @ParentId AND IsDeleted = 0
                ORDER BY CreatedAt ASC";
            
            var replies = await connection.QueryAsync<ProductComment>(sql, new { ParentId = parentId });
            return replies.ToList();
        }

        /// <summary>
        /// 获取留言的点赞数量
        /// </summary>
        public async Task<int> GetLikeCountAsync(Guid commentId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                SELECT COUNT(1) FROM ProductCommentLike 
                WHERE CommentId = @CommentId AND IsDeleted = 0";
            
            return await connection.QuerySingleAsync<int>(sql, new { CommentId = commentId });
        }

        /// <summary>
        /// 检查用户是否已点赞留言
        /// </summary>
        public async Task<bool> IsLikedByUserAsync(Guid commentId, Guid userId)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                SELECT COUNT(1) FROM ProductCommentLike 
                WHERE CommentId = @CommentId AND UserId = @UserId AND IsDeleted = 0";
            
            var count = await connection.QuerySingleAsync<int>(sql, new 
            { 
                CommentId = commentId, 
                UserId = userId 
            });
            
            return count > 0;
        }

        /// <summary>
        /// 更新留言点赞数量
        /// </summary>
        public async Task<bool> UpdateLikeCountAsync(Guid commentId, int increment)
        {
            using var connection = ConnectionFactory.CreateConnection();
            
            var sql = @"
                UPDATE ProductComment 
                SET LikeCount = LikeCount + @Increment, UpdatedAt = @UpdatedAt
                WHERE Id = @CommentId";
            
            var rowsAffected = await connection.ExecuteAsync(sql, new 
            { 
                CommentId = commentId, 
                Increment = increment,
                UpdatedAt = DateTime.UtcNow
            });
            
            return rowsAffected > 0;
        }
    }
}